// Copyright 2022 a.o.smith ALL Rights Reserved
package com.liuxinlong.modules.common.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.liuxinlong.api.SPOInterface;
import com.liuxinlong.api.SPORequestHeaderDto;
import com.liuxinlong.api.SharePoint;
import com.liuxinlong.common.TreeNode;
import com.liuxinlong.constant.ThreadLocalConstants;
import com.liuxinlong.constant.TimeFormatConstants;
import com.liuxinlong.enums.ButlerBusinessTypeEnum;
import com.liuxinlong.enums.DesignStatusEnum;
import com.liuxinlong.modules.common.entity.SelectTreeDto;
import com.liuxinlong.modules.common.entity.StandardSearchDto;
import com.liuxinlong.modules.common.service.DashboardService;
import com.liuxinlong.modules.common.service.TreeService;
import com.liuxinlong.modules.dao.ButlerTrainDao;
import com.liuxinlong.modules.dao.ClassificationDao;
import com.liuxinlong.modules.dao.FileManageDao;
import com.liuxinlong.modules.dao.FileTemporaryDao;
import com.liuxinlong.modules.dao.HierarchyDao;
import com.liuxinlong.modules.dao.HierarchyRelationDao;
import com.liuxinlong.modules.dao.QuestionAnswerDao;
import com.liuxinlong.modules.dao.RoleRightDao;
import com.liuxinlong.modules.dao.StandardContentDao;
import com.liuxinlong.modules.dao.StandardDao;
import com.liuxinlong.modules.dao.StandardNewsDao;
import com.liuxinlong.modules.dao.UserDao;
import com.liuxinlong.modules.entity.ButlerTrain;
import com.liuxinlong.modules.entity.Classification;
import com.liuxinlong.modules.entity.FileManage;
import com.liuxinlong.modules.entity.Hierarchy;
import com.liuxinlong.modules.entity.QuestionAnswer;
import com.liuxinlong.modules.entity.RoleRight;
import com.liuxinlong.modules.entity.SharePointHeader;
import com.liuxinlong.modules.entity.Standard;
import com.liuxinlong.modules.entity.StandardContent;
import com.liuxinlong.modules.entity.User;
import com.liuxinlong.modules.mapper.SharePointHeaderMapper;
import com.liuxinlong.modules.standard.dto.StandardNewsDto;
import com.liuxinlong.utils.ObjectUtils;
import com.liuxinlong.utils.ThreadlocalUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 首页查询服务接口层实现
 *
 * @author liuxinlong@hotwater.com.cn
 * @version 1.0.0
 * @since 2022年1月26日
 */
@Service
@Slf4j
public class DashboardServiceImpl implements DashboardService {

    @Autowired
    private HierarchyDao hierarchyDao;

    @Autowired
    private TreeService treeService;

    @Autowired
    private StandardDao standardDao;

    @Autowired
    private HierarchyRelationDao hierarchyRelationDao;

    @Autowired
    private StandardContentDao standardContentDao;

    @Autowired
    private StandardNewsDao standardNewsDao;

    @Autowired
    private ClassificationDao classificationDao;

    @Autowired
    private FileManageDao fileManageDao;

    @Autowired
    private SPOInterface spoInterface;

    @Autowired
    private SharePoint sharePoint;

    @Autowired
    private SharePointHeaderMapper sharePointHeaderMapper;

    @Autowired
    private FileTemporaryDao fileTemporaryDao;

    @Autowired
    private ButlerTrainDao butlerTrainDao;

    @Autowired
    private QuestionAnswerDao questionAnswerDao;

    @Autowired
    private UserDao userDao;

    @Autowired
    private RoleRightDao roleRightDao;

    @Override
    public Map<String, Object> queryComprehensive(Map<String, Object> queryParam) {
        int startNum = (int) queryParam.get("startNum");
        int pageSize = (int) queryParam.get("pageSize");
        queryParam.put("available", true);
        int label = (int) queryParam.get("label");
        String keyword = (String) queryParam.get("keyword");
//        Pattern pattern = Pattern.compile("^[-\\+]?[\\d]*$");
//        if (pattern.matcher(keyword).matches()) {
//            return localSearch(queryParam);
//        }
        if (label == 1) {
//            if (keyword.contains("-")) {
//                queryParam.put("keyword", keyword.replaceAll("\\-", "   "));
//            }
            return searchStand(startNum, pageSize, queryParam, keyword);
        } else if (label == 2) {
            return searchButler(startNum, pageSize, queryParam, keyword);
//            searchButler
//            Map<String,Object> resultMap = new HashMap<>();
//            resultMap.put("totalNum", 0);
//            return resultMap;
        } else {
            List<Map<String, Object>> dataList = new ArrayList<>();
            int total = 0;
            Map<String, Object> standardMap = searchStand(startNum, pageSize, queryParam, keyword);
            List<Map<String, Object>> standardList = (List<Map<String, Object>>) standardMap.get("dataList");
            int standardTotal = (int) standardMap.get("totalNum");
            dataList.addAll(standardList);
            total = total + standardTotal;
            Map<String, Object> trainMap = searchButler(startNum, pageSize, queryParam, keyword);
            List<Map<String, Object>> trainList = (List<Map<String, Object>>) trainMap.get("dataList");
            int trainTotal = (int) trainMap.get("totalNum");
            dataList.addAll(trainList);
            total = total + trainTotal;
            Map<String, Object> resultMap = new HashMap<>();
            resultMap.put("dataList", dataList);
            resultMap.put("totalNum", total);
            resultMap.put("localMode",standardMap.get("localMode"));
            return resultMap;
        }
//        return localSearch(queryParam);
    }

    /**
     * 标准检索
     *
     * @param startNum
     * @param pageSize
     * @param queryParam 查询参数
     * @param keyword    关键字
     * @return
     */
    private Map<String, Object> searchStand(int startNum, int pageSize, Map<String, Object> queryParam, String keyword) {
        // 先在本地查询，获取数据列表
        List<Standard> localOriginList = standardDao.queryStandardListByParam(queryParam);
        Map<String, Standard> localMap = new HashMap<>();
        for (Standard standard : localOriginList) {
            localMap.put(standard.getId(), standard);
        }
        Map<String, Object> resultMap = new HashMap<>();
        User user = (User) ThreadlocalUtils.getCache(ThreadLocalConstants.USER_INFO);
        SharePointHeader sharePointHeader = sharePointHeaderMapper.selectById("1");
        SPORequestHeaderDto spo = new SPORequestHeaderDto();
        List<Map<String, Object>> dataList = new ArrayList<>();
        boolean localMode = false;
        try {
            if (ObjectUtils.isEmpty(sharePointHeader)) {
                spo = spoInterface.connectSPO(user);
            } else {
                spo.setRequestDigest(sharePointHeader.getRequestDigest());
                spo.setRtFa(sharePointHeader.getRtFa());
                spo.setSecurityToken(sharePointHeader.getSecurityToken());
                spo.setFedAuth(sharePointHeader.getFedAuth());
            }
            log.info("sharePointHeader success!");
            Map<String, Object> dataMap = spoInterface.searchFilePost(spo, keyword, startNum, pageSize);
            dataList = (List<Map<String, Object>>) dataMap.get("dataList");
        } catch (Exception e) {
            log.info("connect spo service failed!");
            log.info(e.getMessage());
            localMode = true;
        }
        List<Map<String, Object>> resultList = completeSPOResult(dataList, localMap, startNum);
        resultMap.put("dataList", resultList);
        resultMap.put("localMode",localMode);
//            resultMap.put("totalNum", dataMap.get("totalNum"));
        resultMap.put("totalNum", resultList.size());
        return resultMap;
    }

    /**
     * 培训文件、FAQ检索
     *
     * @param startNum
     * @param pageSize
     * @param queryParam 查询参数
     * @param keyword    关键字
     * @return
     */
    private Map<String, Object> searchButler(int startNum, int pageSize, Map<String, Object> queryParam, String keyword) {
        List<Map<String, Object>> dataList = new ArrayList<>();
        Map<String, Object> resultMap = new HashMap<>();
        int totalNum = 0;
        User currentUser = (User) ThreadlocalUtils.getCache(ThreadLocalConstants.USER_INFO);
        List<RoleRight> trainRights = roleRightDao.queryUserMenuRight(currentUser.getId(), "train_show");
        if (!ObjectUtils.isEmpty(trainRights)) {
            // 先在本地查询，获取数据列表
            List<ButlerTrain> localOriginList = butlerTrainDao.queryTrainListByParam(queryParam);
//        Map<String, ButlerTrain> localMap = new HashMap<>();
//        for (ButlerTrain butlerTrain : localOriginList) {
//            localMap.put(butlerTrain.getId(), butlerTrain);
//        }
            for (ButlerTrain butlerTrain : localOriginList) {
                Map<String, Object> item = ObjectUtils.object2Map(butlerTrain);
                item.put("name", butlerTrain.getTitle());
                item.put("typeName", "培训文档");
                item.put("statusName", "启用");
                item.put("fileId", butlerTrain.getMainFile());
                item.put("businessName", ButlerBusinessTypeEnum.getNameByValue(butlerTrain.getBusinessType() + 2));
                item.put("showType", 2);
                dataList.add(item);
            }
            totalNum = localOriginList.size();
        }

//        User user = (User) ThreadlocalUtils.getCache(ThreadLocalConstants.USER_INFO);
//        SharePointHeader sharePointHeader = sharePointHeaderMapper.selectById("1");
//        SPORequestHeaderDto spo = new SPORequestHeaderDto();
//        if (ObjectUtils.isEmpty(sharePointHeader)) {
//            spo = spoInterface.connectSPO(user);
//        } else {
//            spo.setRequestDigest(sharePointHeader.getRequestDigest());
//            spo.setRtFa(sharePointHeader.getRtFa());
//            spo.setSecurityToken(sharePointHeader.getSecurityToken());
//            spo.setFedAuth(sharePointHeader.getFedAuth());
//        }
//        Map<String, Object> dataMap = spoInterface.searchFilePost(spo, keyword, startNum, pageSize);
//        List<Map<String, Object>> dataList = (List<Map<String, Object>>) dataMap.get("dataList");
//        List<Map<String, Object>> resultList = completeTrainSPOResult(dataList, localMap, startNum);
//        resultMap.put("dataList", resultList);
//            resultMap.put("totalNum", dataMap.get("totalNum"));
//        resultMap.put("totalNum", resultList.size());
        List<RoleRight> faqRights = roleRightDao.queryUserMenuRight(currentUser.getId(), "faq_show");
        if (!ObjectUtils.isEmpty(faqRights)) {
            Map<String, Map<String, String>> userMap = userDao.getUserMap();
            List<QuestionAnswer> faqList = questionAnswerDao.queryFaqListByParam(queryParam);
            for (QuestionAnswer questionAnswer : faqList) {
                Map<String, Object> item = ObjectUtils.object2Map(questionAnswer);
                item.put("name", questionAnswer.getQuestion());
                item.put("typeName", "FAQ");
                item.put("statusName", "启用");
                item.put("showType", 3);
                item.put("cover", 3);
                item.put("businessName", ButlerBusinessTypeEnum.FAQ.getName());
                item.put("content", questionAnswer.getAnswer());
                item.put("shareUser", (StringUtils.isEmpty(questionAnswer.getUpdateUser()) ? userMap.get(questionAnswer.getCreateUser()) : userMap.get(questionAnswer.getUpdateUser())).get("name"));
                dataList.add(item);
            }
            totalNum = totalNum + faqList.size();
        }

        resultMap.put("dataList", dataList);
        resultMap.put("totalNum", totalNum);
        return resultMap;
    }

    /**
     * 本地检索（不从云端文件夹获取数据）
     *
     * @param queryParam 查询参数
     * @return 检索结果数据
     */
    private Map<String, Object> localSearch(Map<String, Object> queryParam) {
        int startNum = (int) queryParam.get("startNum");
        int pageSize = (int) queryParam.get("pageSize");

        int label = (int) queryParam.get("label");
        String keyword = (String) queryParam.get("keyword");
        List<Standard> originList = standardDao.queryStandardListByParam(queryParam);
        List<Map<String, Object>> dataList = completeResult(originList, startNum, label, keyword);
        Map<String, Map<String, Object>> productMap = standardDao.queryStandardProductMap(queryParam);
        List<Classification> classificationList = classificationDao.getParentClassificationList();
        List<SelectTreeDto> productTree = new ArrayList<>(productMap.size());
        for (Classification classification : classificationList) {
            if (!productMap.containsKey(classification.getId())) {
                continue;
            }
            String key = classification.getId();
            SelectTreeDto cla = new SelectTreeDto();
            cla.setKey(key);
            cla.setTitle(classification.getName());
            Map<String, Object> info = productMap.get(key);
            cla.setNum(((Number) info.get("num")).intValue());
            productTree.add(cla);
        }
        Map<String, Map<String, Object>> rangeMap = standardDao.queryStandardRangeMap(queryParam);
        List<SelectTreeDto> rangeTree = new ArrayList<>(rangeMap.size());
        for (Object key : rangeMap.keySet()) {
            String title = ((Integer) key) == 1 ? "设计标准" : ((Integer) key) == 2 ? "测试标准" : "设计&测试标准";
            SelectTreeDto range = new SelectTreeDto();
            range.setKey(String.valueOf(key));
            range.setTitle(title);
            Map<String, Object> info = rangeMap.get(key);
            range.setNum(((Number) info.get("num")).intValue());
            rangeTree.add(range);
        }
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("dataList", dataList);
        resultMap.put("productTree", productTree);
        resultMap.put("rangeTree", rangeTree);
        int total = countComprehensive(queryParam);
        resultMap.put("totalNum", total);
        return resultMap;
    }

    @Override
    public int countComprehensive(Map<String, Object> queryParam) {
        return standardDao.countStandardListByParam(queryParam);
    }

    @Override
    public TreeNode queryKnowledgeTree() {
        List<Hierarchy> hierarchyList = hierarchyDao.getHierarchyList();
        List<TreeNode> bodyList = new ArrayList<>();
        for (Hierarchy hierarchy : hierarchyList) {
            TreeNode treeNode = new TreeNode();
            treeNode.setId(hierarchy.getId());
            treeNode.setName(hierarchy.getName());
            treeNode.setValue(hierarchy.getName());
            treeNode.setParentId(hierarchy.getParentId());
            bodyList.add(treeNode);
        }
        TreeNode root = new TreeNode();
        root.setId("0");
        root.setName("AOS");
        root.setValue("AOS");
        root.setChildren(new ArrayList<>());
        treeService.getChild(root, bodyList, new HashMap<>(), 1, 0);
        return root;
    }

    @Override
    public TreeNode queryKnowledgeGraph(String rootId, int deep) {
        List<Hierarchy> hierarchyList = hierarchyDao.getHierarchyList();
        List<TreeNode> bodyList = new ArrayList<>();
        TreeNode root = new TreeNode();
        root.setId("0");
        root.setName("AOS");
        root.setValue("AOS");
        root.setChildren(new ArrayList<>());
        for (Hierarchy hierarchy : hierarchyList) {
            TreeNode treeNode = new TreeNode();
            treeNode.setId(hierarchy.getId());
            treeNode.setName(hierarchy.getName());
            treeNode.setValue(hierarchy.getName());
            treeNode.setParentId(hierarchy.getParentId());
            bodyList.add(treeNode);
            if (StringUtils.equals(rootId, hierarchy.getId())) {
                root = treeNode;
            }
        }
        getChild(root, bodyList, new HashMap<>(), 1, deep);
        return root;
    }

    @Override
    public Map<String, Object> queryRootDetail(String id) {
        Map<String, Object> queryMap = new HashMap<>();
        if (!StringUtils.equals(id, "0")) {
            queryMap.put("hierarchy", id);
        }
        int designNum = standardDao.getStandardCount(queryMap);
        Map<String, Object> map = new HashMap<>();
        map.put("designNum", designNum);
        map.put("testNum", 0);
        map.put("caseNum", 0);
        return map;
    }

    @Override
    public Map<String, Object> queryNewsRotation() {
        Map<String, Object> resultMap = new HashMap<>();
        Map<String, Object> query = new HashMap<>();
        query.put("startNum", 0);
        query.put("pageSize", 10);
        List<Map<String, Object>> newsList = queryStandardNews(query);
        resultMap.put("newsList", newsList);
        List<StandardSearchDto> searchDtoList = fileTemporaryDao.querySearchTopTen();
        List<Map<String, Object>> searchList = new ArrayList<>(searchDtoList.size());
        int searchSort = 1;
        for (StandardSearchDto searchDto : searchDtoList) {
            Map<String, Object> map = ObjectUtils.object2Map(searchDto);
            map.put("sort", searchSort);
            searchList.add(map);
            searchSort++;
        }
        resultMap.put("searchList", searchList);
        return resultMap;
    }

    @Override
    public List<Map<String, Object>> queryStandardNews(Map<String, Object> queryParam) {
        List<StandardNewsDto> originList = standardNewsDao.pageNewsList(queryParam);
        List<Map<String, Object>> newsList = new ArrayList<>(originList.size());
        int sort = 1;
        Date currentTime = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(TimeFormatConstants.YYYY_MM_DD_HH_MM_SS);
        for (StandardNewsDto item : originList) {
            Map<String, Object> map = ObjectUtils.object2Map(item);
            String preposition = " ";
            try {
                Date operateTime = simpleDateFormat.parse(item.getOperateTime());
                preposition = operateTime.before(currentTime) ? " 已在 " : " 将在 ";
            } catch (Exception e) {
                log.info("时间转换失败：{} ", item.getOperateTime());
            }
            String content = item.getMainStandardSn() + " " + item.getMainStandardName() + " " + preposition + item.getOperateTime().substring(0, 10) + "  "
                    + (item.getOperateType() == 1 ? "实施" : item.getOperateType() == 2 ? "作废" : "修订")
                    + (StringUtils.isEmpty(item.getOtherStandard()) ? "" : item.getOperateType() == 1 ?
                    "，替换 " + item.getOtherStandardSn() + " " + item.getOtherStandardName() :
                    "，被 " + item.getOtherStandardSn() + " " + item.getOtherStandardName() + " 替换");
            map.put("sort", sort);
            map.put("content", content);
            map.put("preposition", preposition);
            newsList.add(map);
            sort++;
        }
        return newsList;
    }

    @Override
    public int countStandardNews(Map<String, Object> queryParam) {
        return standardNewsDao.getNewsCount(queryParam);
    }

    private void getChild(TreeNode parent, List<TreeNode> bodyList, Map<String, String> map, int currentDeep,
                          int targetDeep) {
        List<TreeNode> childList = new ArrayList<>();
        int nextDeep = currentDeep + 1;
        if (targetDeep != 0 && currentDeep == targetDeep) {
            parent.setChildren(childList);
            return;
        }
        // Map<当前层级,Map<当前层级，子层级>>
        Map<String, Map<String, String>> hierarchyRelationMap = hierarchyRelationDao.queryRelationMap(parent.getId());
        bodyList.stream().filter(c -> !map.containsKey(c.getId())).filter(c -> c.getParentId().equals(parent.getId()))
                .forEach(c -> {
                    if (ObjectUtils.isEmpty(hierarchyRelationMap) || !hierarchyRelationMap.containsKey(c.getId())) {
                        map.put(c.getId(), c.getParentId());
                    }
                    this.getChild(c, bodyList, map, nextDeep, targetDeep);
                    childList.add(c);
                });
        if (!ObjectUtils.isEmpty(hierarchyRelationMap)) {
            bodyList.stream().filter(c -> !map.containsKey(c.getId()))
                    .filter(c -> StringUtils.equals(c.getParentId(), "-1"))
                    .filter(c -> !hierarchyRelationMap.containsKey(c.getId())).forEach(c -> {

                        this.getChild(c, bodyList, map, nextDeep, targetDeep);
                        childList.add(c);
                    });
        }

        parent.setChildren(childList);
    }

    /**
     * 补全数据
     *
     * @param originList 原始数据
     * @param startNum   起始数
     * @param label      查询类型
     * @param keyword    查询关键字
     * @return 补全数据列表
     */
    private List<Map<String, Object>> completeResult(List<Standard> originList, int startNum,
                                                     int label, String keyword) {
        List<Map<String, Object>> resultList = new ArrayList<>();
        if (ObjectUtil.isEmpty(originList)) {
            return resultList;
        }
        Set<String> mainFileList = originList.stream().map(Standard::getMasterPdfFile).collect(Collectors.toSet());
        Map<String, String> mainFileMap = new HashMap<>();
        Map<String, String> mainFileTypeMap = new HashMap<>();
        if (!mainFileList.isEmpty()) {
//            mainFileMap = fileManageDao.getFileMapByIds(mainFileList);
            List<FileManage> fileManageList = fileManageDao.selectBatchIds(mainFileList);
            for (FileManage fileManage : fileManageList) {
                mainFileMap.put(fileManage.getId(), fileManage.getPreviewPath());
                mainFileTypeMap.put(fileManage.getId(), fileManage.getFileType());
            }
        }

        Map<String, Map<String, String>> classificationMap = classificationDao.getClassificationMap();
        int sort = startNum + 1;
        for (Standard item : originList) {
            Map<String, Object> map = ObjectUtils.object2Map(item);
            map.put("sort", sort);

            StandardContent sc = standardContentDao.getStandardContent(item.getId());
            if (!ObjectUtils.isEmpty(sc)) {
                String newContent;
                String content = sc.getContent();
                int position = label == 3 ? content.indexOf(keyword) : 0;
                int start = 0;
                int end = position + keyword.length() + 200;
                if (position > 10) {
                    start = position - 10;
                }
                newContent = content.substring(start, Math.min(end, content.length()));
                map.put("content", newContent);
            }
            Map<String, String> classificationInfo = classificationMap.get(item.getClassification());
            if (!ObjectUtils.isEmpty(classificationInfo)) {
                map.put("classificationName", classificationInfo.get("name"));
            }
            map.put("thumbnail", mainFileMap.getOrDefault(item.getMasterFile(), ""));
            map.put("fileType", mainFileTypeMap.getOrDefault(item.getMasterFile(), ""));
            map.put("statusName", DesignStatusEnum.getNameByValue(item.getStatus()));
            map.put("typeName", item.getStandardType() == 1 ? "设计标准" : item.getStandardType() == 2 ? "测试标准" : "设计&测试标准");
            map.put("fileId", item.getMasterPdfFile());
            resultList.add(map);
            sort++;
        }
        return resultList;
    }

    /**
     * 补全数据
     *
     * @param originList 原始数据
     * @param localMap   本地查询结果
     * @param startNum   数据起始值
     * @return 补全数据列表
     */
    private List<Map<String, Object>> completeSPOResult(List<Map<String, Object>> originList, Map<String, Standard> localMap, int startNum) {
        List<Map<String, Object>> resultList = new ArrayList<>();
        Set<String> fileIdSet = new HashSet<>();
        for (Map<String, Object> item : originList) {
            if (!item.containsKey("fileName")) {
                continue;
            }
            if (!String.valueOf(item.get("fileName")).contains(".")) {
                continue;
            }

            String spoFileId = String.valueOf(item.get("fileName")).split("\\.")[0];
            fileIdSet.add(spoFileId);
            item.put("spoFileId", spoFileId);
            item.put("showType", 1);
        }
        Map<String, Map<String, Object>> fileMap = new HashMap<>();
        if (!ObjectUtils.isEmpty(fileIdSet)) {
            fileMap = fileManageDao.getFileMapByIds(fileIdSet);
        }

        Map<String, Map<String, String>> standardMap = standardDao.getAllStandardMap();
        int sort = startNum + 1;
        for (Map<String, Object> item : originList) {
            item.put("sort", sort);
            if (fileMap.containsKey(item.get("spoFileId"))) {
                String standardId = String.valueOf(fileMap.get(item.get("spoFileId")).get("businessId"));
                Standard standard;
                if (localMap.containsKey(standardId)) {
                    standard = localMap.get(standardId);
                    localMap.remove(standardId);
                } else {
                    log.info("标准id： {} ...", standardId);
                    standard =
                            JSONObject.parseObject(JSONObject.toJSONString(standardMap.get(standardId)), Standard.class);
                    if (ObjectUtils.isEmpty(standard)) {
                        log.info("标准类型： {} 未匹配到...", standardId);
                        continue;
                    }
                    if (standard.getStatus() == DesignStatusEnum.REPEALED.getValue()) {
                        log.info("标准： {}已废止...", standard.getStandardSn());
                        continue;
                    }
                }
                if (!ObjectUtils.isEmpty(standard)) {
                    item.put("standardSn", standard.getStandardSn());
                    item.put("name", standard.getName());
                    item.put("statusName", DesignStatusEnum.getNameByValue(standard.getStatus()));
                    item.put("typeName", standard.getStandardType() == 1 ? "设计标准" : standard.getStandardType() == 2 ? "测试标准" : "设计&测试标准");
                    item.put("securityLevel", standard.getSecurityLevel());
                    item.put("version", standard.getVersion());
//                    if (!ObjectUtils.isEmpty(standard.getMasterPdfFile())) {
//                        FileManage pdfFile = fileManageDao.selectById(standard.getMasterPdfFile());
//                        item.put("fileId", standard.getSecurityLevel());
//                    }
                    item.put("fileId", standard.getMasterPdfFile());
                    item.put("showType", 1);
                } else {
                    log.info("无匹配标准信息...");
                    continue;
                }
//                item.put("fileId", item.get("spoFileId"));
            } else {
                log.info("无匹配标准信息...{}", item.get("spoFileId"));
                continue;
            }
            resultList.add(item);
            sort++;
        }
        if (!localMap.isEmpty()) {
            for (Standard standard : localMap.values()) {
                Map<String, Object> item = ObjectUtils.object2Map(standard);
                item.put("sort", sort);
                item.put("standardSn", standard.getStandardSn());
                item.put("name", standard.getName());
                item.put("statusName", DesignStatusEnum.getNameByValue(standard.getStatus()));
                item.put("typeName", standard.getStandardType() == 1 ? "设计标准" : standard.getStandardType() == 2 ? "测试标准" : "设计&测试标准");
                item.put("securityLevel", standard.getSecurityLevel());
                item.put("version", standard.getVersion());
                item.put("fileId", standard.getMasterPdfFile());
                item.put("showType", 1);
                resultList.add(item);
                sort++;
            }
        }
        return resultList;
    }

    /**
     * 补全数据
     *
     * @param originList 原始数据
     * @param localMap   本地查询结果
     * @param startNum   数据起始值
     * @return 补全数据列表
     */
    private List<Map<String, Object>> completeTrainSPOResult(List<Map<String, Object>> originList, Map<String, ButlerTrain> localMap, int startNum) {
        List<Map<String, Object>> resultList = new ArrayList<>();
        Set<String> fileIdSet = new HashSet<>();
        for (Map<String, Object> item : originList) {
            if (!item.containsKey("fileName")) {
                continue;
            }
            if (!String.valueOf(item.get("fileName")).contains(".")) {
                continue;
            }

            String spoFileId = String.valueOf(item.get("fileName")).split("\\.")[0];
            fileIdSet.add(spoFileId);
            item.put("spoFileId", spoFileId);
        }
        Map<String, Map<String, Object>> fileMap = new HashMap<>();
        if (!ObjectUtils.isEmpty(fileIdSet)) {
            fileMap = fileManageDao.getFileMapByIds(fileIdSet);
        }

        Map<String, Map<String, String>> trainMap = butlerTrainDao.getAllTrainMap();
        int sort = startNum + 1;
        for (Map<String, Object> item : originList) {
            item.put("sort", sort);
            if (fileMap.containsKey(item.get("spoFileId"))) {
                String trainId = String.valueOf(fileMap.get(item.get("spoFileId")).get("businessId"));
                ButlerTrain train;
                if (localMap.containsKey(trainId)) {
                    train = localMap.get(trainId);
                    localMap.remove(trainId);
                } else {
                    train =
                            JSONObject.parseObject(JSONObject.toJSONString(trainMap.get(trainId)), ButlerTrain.class);
                }
                if (!ObjectUtils.isEmpty(train)) {
                    item.put("standardSn", train.getTitle());
                    item.put("name", train.getTitle());
                    item.put("statusName", DesignStatusEnum.PUBLISHED.getName());
                    item.put("typeName", "培训文档");
                    item.put("securityLevel", 0);
                    item.put("version", 0);
//                    if (!ObjectUtils.isEmpty(standard.getMasterPdfFile())) {
//                        FileManage pdfFile = fileManageDao.selectById(standard.getMasterPdfFile());
//                        item.put("fileId", standard.getSecurityLevel());
//                    }
                    item.put("fileId", train.getCover());
                }
//                item.put("fileId", item.get("spoFileId"));
            }
            resultList.add(item);
            sort++;
        }
        if (!localMap.isEmpty()) {
            for (ButlerTrain train : localMap.values()) {
                Map<String, Object> item = ObjectUtils.object2Map(train);
                item.put("sort", sort);
                item.put("standardSn", train.getTitle());
                item.put("name", train.getTitle());
                item.put("statusName", DesignStatusEnum.PUBLISHED.getName());
                item.put("typeName", "培训文档");
                item.put("securityLevel", 0);
                item.put("version", 0);
                item.put("fileId", train.getCover());
                resultList.add(item);
                sort++;
            }
        }
        return resultList;
    }

}
